package com.oa.web.action;

import com.oa.bean.Dept;
import com.oa.utils.PageBean;
import com.oa.service.DeptService;
import com.oa.web.action.base.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
public class DeptAction extends BaseAction<Dept> {

    @Autowired
    private DeptService deptService;


    //监听排序
    private String field;//排序字段
    private String order;//排序方式


    //分页查询
    public String pageQuery() {

        // 排序
        if (StringUtils.isNotBlank(field) && StringUtils.isNotBlank(order)) {

            DetachedCriteria dc = pageBean.getCriteria();

            if (order.equals("desc")) {
                dc.addOrder(Order.desc(field));
            }

            if (order.equals("asc")) {
                dc.addOrder(Order.asc(field));
            }

        }

        // 查询是否删除
        if (model.getIs() != null) {
            DetachedCriteria dc = pageBean.getCriteria();
            dc.add(Restrictions.eq("is", model.getIs()));
        }

        PageBean pb = deptService.pageQuery(this.pageBean);

        this.writeObj2Json(pb, new String[]{"currentPage", "pageSize", "criteria", "dept", "customers"});

        return NONE;
    }

    //查询所有部门
    public String pageQueryAllInfos() {
        DetachedCriteria dc = this.pageBean.getCriteria();
        dc.add(Restrictions.eq("is", 1));

        PageBean pb = deptService.pageQuery(this.pageBean);
        this.writeObj2Json(pb, new String[]{"currentPage", "pageSize", "criteria", "emps"});
        return NONE;
    }

    //保存或者修改
    public String addOrUpdate() {
        //清除访问修改之前的部门缓存
        session.remove("dept");
        deptService.saveOrUpdate(this.model);
        this.writeText("success");
        return NONE;
    }


    //检查部门是否存在
    public String checkDept() {

        Dept dept = deptService.checkDept(this.model.getName());

        if (dept != null) {
            this.writeText("exists");
        }

        return NONE;
    }

    //修改部门
    public String getDeptBeforeUpdate() {

        Dept dept = deptService.findDeptById(model.getId());

        session.put("dept", dept);

        return "update";
    }

    //清除之前缓存的部门信息
    public String cleanDept() {
        session.remove("dept");
        return NONE;
    }

    //删除部门
    public String delete() {

        String msg = deptService.delete(this.model);
        this.writeText(msg);
        return NONE;
    }

    //获取所有部门
    public String findAll() {

        List<Dept> list = deptService.findAll();

        this.writeList2Json(list, new String[]{"emps", "is", "remark"});

        return NONE;
    }

    public String findAllDeptNames() {

        List<Dept> list = deptService.findAllDeptNames();
        this.writeList2Json(list, new String[]{"emps", "is", "remark"});
        return NONE;
    }


    //恢复部门
    public String restoreDept() {

        deptService.restoreDept(this.model.getId());

        this.writeText("true");

        return NONE;
    }


    //检查部门能否被撤销
    public String checkCanDeleted() {

        List<String> list = deptService.checkCanDeleted(model.getId());

        String msg = "";
        if (list != null && list.size() > 0) {
            msg = "false";
        } else {
            msg = "true";
        }

        Map<String, Object> map = new HashMap<>();

        map.put("msg", msg);
        map.put("list", list);

        this.writeObj2Json(map, new String[]{});

        return NONE;
    }

    //检查部门是否存在部门主管

    public String checkFlag() {

        boolean check = deptService.checkFlag(model.getId());

        this.writeText(check + "");

        return NONE;
    }

    //导出所有部门
    public String exportDepts() throws IOException {

        List<Dept> depts = deptService.findAll();

        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet sheet = workbook.createSheet();

        HSSFRow header = sheet.createRow(0);

        header.createCell(0).setCellValue("部门编号");
        header.createCell(1).setCellValue("部门名称");
        header.createCell(2).setCellValue("部门备注");
        header.createCell(3).setCellValue("是否作废!(1:正常,0:作废)");

        int i = 1;
        for (Dept dept : depts) {

            Integer id = dept.getId();
            String name = dept.getName();
            String remark = dept.getRemark();
            Integer is = dept.getIs();

            HSSFRow row = sheet.createRow(i++);

            row.createCell(0).setCellValue(id);
            row.createCell(1).setCellValue(name);
            row.createCell(2).setCellValue(remark);
            row.createCell(3).setCellValue(is);

        }

        HttpServletResponse response = ServletActionContext.getResponse();

        // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        String fileName = "部门数据.xls";
        fileName = URLEncoder.encode(fileName, "utf-8");
        // 2.设置文件头：最后一个参数是设置下载文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        // 输出文件
        workbook.write(response.getOutputStream());

        return NONE;
    }


    public void setField(String field) {
        this.field = field;
    }

    public void setOrder(String order) {
        this.order = order;
    }
}
